// src/main/java/com/bookmanager/controller/AddUserController.java
package com.bookmanager.controller;

import com.bookmanager.model.User;
import com.bookmanager.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/admin/add-user")
public class AddUserController extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 直接跳转到添加用户页面
        response.sendRedirect("../admin/user-add.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        // 检查管理员权限
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        // 获取表单参数
        String userId = request.getParameter("userId");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String role = request.getParameter("role");

        // 创建用户对象
        User user = new User();
        user.setUserId(userId);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setRole(role);

        // 调用服务层注册用户
        String result = userService.register(user, confirmPassword);

        if ("success".equals(result)) {
            request.setAttribute("message", "用户添加成功！");
            request.setAttribute("messageType", "success");
        } else {
            request.setAttribute("message", "添加失败：" + result);
            request.setAttribute("messageType", "error");
            // 回填表单数据
            request.setAttribute("formData", user);
        }

        // 转发回添加页面显示结果
        request.getRequestDispatcher("/admin/user-add.jsp").forward(request, response);
    }
}